<template>
    <div>
      <div class="tinymce-editor" v-loading="loading" element-loading-text="上传中" element-loading-spinner="el-icon-loading">
        <!-- 同一页面使用多个编辑器时必须传入id参数，否则只有第一个编辑器会生效-->
        <editor :id="editorId" v-model="editorValue" :disabled="disabledIn" :init="editorInit" />
        <div class="tinymce-upload-progress-box">
          <div class="display-upload-wrapper">
            <div class="innier-upload-wrapper">
  
            </div>
          </div>
          <!-- <el-progress type="circle" ref="uploadProgress" :color="colors" class="tinymce-upload-progress"
            :percentage="uploadPrecent" />
        </div> -->
        </div>
      </div>
    </div>
  </template>
  
  <script>
  import { uploadfile, breakpointUploadFile, addFile, checkFile } from "./../api/index";
  import axios from 'axios';
  /*
  使用public本地库
  */
  // 引入tinymce主件
  import tinymce from "../../public/tinymce/tinymce";
  // 引入tinymce-vue组件
  import Editor from "@tinymce/tinymce-vue";
  import "tinymce/icons/default/icons";
  // 必须引入主体才能汉化和显示
  import "../../public/tinymce/themes/silver";
  import "../../public/tinymce/zh_CN";
  // import '../../../public/tinymce/icons/default/icons'
  // 引入富文本编辑器主题的js和css
  import "../../public/tinymce/themes/silver/theme.min";
  import "../../public/tinymce/skins/ui/oxide/skin.min.css";
  // 扩展插件
  import "../../public/tinymce/plugins/image";
  import "../../public/tinymce/plugins/link";
  import "../../public/tinymce/plugins/code";
  import "../../public/tinymce/plugins/table";
  import "../../public/tinymce/plugins/lists";
  import "../../public/tinymce/plugins/wordcount"; // 字数统计插件
  import "../../public/tinymce/plugins/media"; // 插入视频插件
  import "../../public/tinymce/plugins/template"; // 模板插件
  import "../../public/tinymce/plugins/fullscreen";
  import "../../public/tinymce/plugins/paste";
  import "../../public/tinymce/plugins/preview";
  import "../../public/tinymce/plugins/contextmenu";
  import "../../public/tinymce/plugins/textcolor";
  import '../../public/tinymce/plugins/indent2em/plugin' // 首行缩进
  import md5 from 'js-md5'
  // 首行缩进插件需单独下载后将下载文件放在plugins下
  export default {
    name: "Tinymce",
    components: {
      Editor,
    },
    props: {
      type: {
        type: Number,
        default: 0,
      },
      height: {
        type: Number,
        default: 500,
      },
      id: {
        type: String,
        default: "tinymceEditor",
      },
      value: {
        type: String,
        default: "",
      },
      disabledIn: {
        type: Boolean,
        default: false,
      },
      plugins: {
        type: [String, Array],
        default:
          "link lists image code table wordcount media fullscreen preview paste indent2em",
      },
      toolbar: {
        type: [String, Array],
        default:
          "lineHeight|fontselect | bold italic underline strikethrough | link unlink image media | undo redo | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | indent2em outdent indent blockquote | code | removeformat",
      },
    },
  
    data() {
      return {
        baseUrl:"http://139.215.190.237:8081/api",
        uploadPrecent: 0,
        dialogVisible: false,
        list: [],
        loading: false,
        uploadUrl1: "/api/management/addNews/uploadfile",
        uploadUrl2: "/api/management/files/breakpoint-upload",
        editorInit: {
          language_url: "../../public/tinymce/zh_CN.js",
          language: "zh_CN",
          skin_url: "/public/tinymce/skins/ui/oxide/",
          content_css: "/public/tinymce/skins/content/default/content.css",
          height: this.height,
          content_style:
            "* { padding:0; margin:0; } img {max-width:100% !important; display: block; } video { max-width:100% !important; display: block; }",
          plugin_preview_width: 375, // 预览宽度
          plugin_preview_height: 668,
          lineheight_val:
            "1 1.1 1.2 1.3 1.35 1.4 1.5 1.55 1.6 1.75 1.8 1.9 1.95 2 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 3 3.1 3.2 3.3 3.4 4 5",
          fontsize_formats:
            "8px 10px 11px 12px 13px 14px 15px 16px 17px 18px 24px 36px",
          font_formats:
            "微软雅黑='微软雅黑';宋体='宋体';黑体='黑体';仿宋='仿宋';楷体='楷体';隶书='隶书';幼圆='幼圆';Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings",
          plugins: this.plugins,
          indent2em_val: "2em", // 首行缩进
          powerpaste_word_import: "merge",
          toolbar: this.toolbar,
          paste_data_images: true,
          statusbar: true, // 底部的状态栏
          menubar: false, // 最上方的菜单
          branding: false, // 水印“Powered by TinyMCE”
          convert_urls: false, // 去除URL转换
          // 图片自定义上传
          images_upload_handler: (blobInfo, success, failure) => {
            console.log(blobInfo);
            const fileData = new FormData();
            fileData.append("file", blobInfo.blob());
            // this.dealFile(blobInfo)
            // return
            // 调用上传接口
            uploadfile(fileData).then(({ data, status, msg }) => {
              console.log(data, "data");
              if (data.msg == "SUCCESS") {
                success(data.data);
              } else {
                this.$message.error("上传失败");
              }
            });
          },
          file_picker_callback: (callback, value, meta) => {
            const _tath = this;
            var filetype =
              ".pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4";
            var materialType = "";
            switch (meta.filetype) {
              case "image":
                filetype = ".jpg, .jpeg, .png, .gif";
                materialType = "1";
                break;
              case "media":
                filetype = ".mp3, .mp4";
                break;
              case "file":
              default:
            }
            var input = document.createElement("input");
            input.setAttribute("type", "file");
            input.setAttribute("accept", filetype);
            input.click();
            input.onchange = function () {
              let this_ = this
              var file = this.files[0];
              if (file.type == "video/mp4" || file.type.indexOf("video") != -1) {
                materialType = "3";
              } else if (
                file.type == "audio/mpeg" ||
                file.type == "audio/mp3" ||
                file.type.indexOf("audio") != -1
              ) {
                materialType = "2";
              }
              if (materialType == "1") {
                // 图片上传
                const fileData = new FormData();
                fileData.append("file", file);
                uploadfile(fileData).then(({ data, status, msg }) => {
                  console.log(data, "data");
                  if (data.msg == "SUCCESS") {
                    // 成功则将返回的url传入callback回调函数中
                    // callback 接受两个参数， url 和 图片名称
                    // 注意图片名称必须要传
                    callback(data.data, { title: file.name });
                  } else {
                    this.$message.error("上传失败,请重新上传");
                  }
                });
                input.value = ''
              } else {
                this.loading = true
                const fileData = new FormData();
                fileData.append("file", file);
                fileData.append("materialType", materialType);
                let progressBox = document.getElementsByClassName('tinymce-upload-progress-box')[0]
                progressBox.style.display = 'block'
                progressBox.style.visibility = 'visible'
                // let dialog = document.createElement('div')//'.tox-dialog-wrap div[role="dialog"]';
                // dialog.classList.add('tox-dialog-wrap')
                // let progress = document.createElement("div")
                // progress.classList.add("tinymce-upload-progress")
                // let progressBar = document.createElement("div")
                // progressBar.classList.add("progress-bar");
                // let sourceBox = document.createElement("div").classList.add("tinymce-upload-progress-box")
                // console.log(dialog, progress, progressBar, "progressBar")
                // progressBar.appendChild(progress)
                // dialog.appendChild(progressBar)
                // progressBox.appendChild(dialog)
                // progress.style.display = 'block';
                let innier_upload_wrapper = document.getElementsByClassName('innier-upload-wrapper')[0]
                // let progress__text = document.getElementsByClassName('el-progress__text')[0]
                // my_upload(uploader) {
                axios({
                  method: 'post',
                  headers: {
                    "Content-Type": "multipart/form-data"
                  },
                  url: this.baseUrl+'/api/management/addNews/uploadfile',//自定义上传url
                  data: fileData,
                  onUploadProgress: progressEvent => {
                    let percent = (progressEvent.loaded / progressEvent.total * 100) | 0
                    console.log(percent, "hh")
                    this_.uploadPrecent = percent
                    // progress__text.innerHTML = percent + '%'
                    innier_upload_wrapper.innerHTML = percent + '%'
                    innier_upload_wrapper.style.backgroundSize = `${this.uploadPrecent}% 100%`;
                    if (this_.uploadPrecent == 100) {
                      progressBox.style.display = 'none'
                    }
                  }
                }).then((res) => {
                  input.value = ''
                  if (res.data.msg == "SUCCESS") {
                    callback(res.data.data, { title: file.name });
                    this.$message.success('上传完成');
                  } else {
                    this.$message.error('上传失败');
                  }
                }).catch((err) => {
                  input.value = ''
                  console.log(err)
                  // this.$message.error(err);
                })
                return
                uploadfile(fileData).then(({ data, code, msg }) => {
                  if (data.msg == "SUCCESS") {
                    callback(data.data, { title: file.name });
                  } else {
                    this.$message.error("上传失败,请重新上传");
                  }
                });
                this.loading = false
                input.value = ''
              }
            };
          },
        },
        editorId: this.id,
        newValue: "",
      };
    },
    computed: {
      innerUploadStyle() {
        return `background-size: ${this.uploadPrecent}% 100%;`
      },
      editorValue: {
        get() {
          return this.value;
        },
        set(val) {
          this.newValue = val;
        },
      },
    },
    watch: {
      newValue(newValue) {
        this.$emit("input", newValue);
      },
    },
    mounted() { 
    },
    beforeDestroy() {
      this.clear();
    },
    methods: {
  
      // dealFile(data) {
      //   // 根据文件大小来分片
      //   let size = data.file.size();
      //   // 假设1024一片，可根据实际来进行，也可以调接口进行
      //   let count = Math.ceil(size / 1024);
      //   for (let i = 0; i < count; i++) {
      //     let item = {
      //       // 放一些必要的东西，例如后端需要啥就给啥
      //       size: 1024,
      //       current: i,
      //       file: data.file.slice(i * 1024, (i + 1) * 1024),
      //     };
      //     this.list.push(item);
      //   }
      //   this.limitUpload(3); // 并发控制，此处设置3，可以设置其他
      // },
      // // 每一片上传
      // uploadSplice(params) {
      //   let _this = this;
      //   let formData = new FormData();
      //   let param = params[0];
      //   formData.append("size", param.size); // 额外参数
      //   // 其他参数不一一列举
      //   return new Promise(function (resolve, reject) {
      //     this.$http
      //       .post("/api/management/files/breakpoint-upload", formData)
      //       .then((res) => {
      //         if (res) {
      //           // 接口成
  
      //           resolve(res.data);
      //         } else {
      //           // 如果出错了，继续执行，前三次错误还会重新请求
      //           if (param.uploadTime < 4) {
      //             param.uploadTime += 1;
      //             _this.list.push(param);
      //           }
      //           resolve(res.message);
      //         }
      //       });
      //   });
      // },
      // limitUpload(max) {
      //   let self = this;
      //   const tempList = [];
      //   const initSize = Math.min(this.list.length, max);
      //   for (let i = 0; i < initSize; i++) {
      //     // 一次性放入初始的个数
      //     tempList.push(run(this.list.splice(0, 1)));
      //   }
      //   // r 代表promise完成的resolve回调函数
      //   // r 函数无论什么样的结果都返回promise，来确保最终promise.all可以正确执行
      //   function r() {
      //     if (self.list.length === 0) {
      //       return Promise.resolve();
      //     }
      //     return run(self.list.splice(0, 1));
      //   }
      //   // 调用一次请求
      //   function upload(url) {
      //     return self.uploadSplice(url).then(r);
      //   }
      //   // 全部请求完成的回调
      //   Promise.all(tempList).then((res) => {
      //     let formData = new FormData();
      //     formData.append("size", size); // size自己定义和获取
      //     this.$http
      //       .post("/api/management/files/breakpoint-upload", formData)
      //       .then((res3) => {
      //         if (res3) {
      //           // 合并，看具体需求，不需要就删除
      //         }
      //       });
      //   });
      // },
  
      clear() {
        this.editorValue = "";
      },
    },
  };
  </script>
  
  <style  scoped>
  .tinymce-upload-progress-box {
    position: fixed;
    background-color: #ffffffbf;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    /* display: none; */
    visibility: hidden;
    z-index: 99991;
  }
  
  .display-upload-wrapper {
    border: 1px solid #207AB7;
    width: 100%;
    text-align: center;
    height: 20;
    border-radius: 0px;
    background: #F4F8FF;
  }
  
  .innier-upload-wrapper {
    height: 100%;
    background: linear-gradient(270deg, #C0D8FF 0%, #207AB7 100%);
    background-repeat: no-repeat;
    background-size: 10% 100%;
    transition: background-size .3s linear;
  }
  
  /* .tox-dialog-wrap .progress-bar {
    position: absolute;
    background-color: #ffffffbf;
    width: 100%;
    height: 100%;
    z-index: 99991;
  } */
  
  .tinymce-upload-progress {
    position: fixed !important;
    text-align: center;
    /* display: none; */
    top: 50%;
    left: 50%;
    z-index: 99991;
    margin-top: -62px !important;
    margin-left: -63px !important;
  }
  </style>
  